package com.yunxi.service.iam.dubbo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yunxi.baseDataToHub.pojo.iam.*;
import com.yunxi.baseDataToHub.pojo.iam.IamOrg;
import com.yunxi.baseDataToHub.pojo.iam.IamPos;
import com.yunxi.baseDataToHub.pojo.iam.IamStaff;
import com.yunxi.baseDataToHub.service.iam.IamDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.util.*;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.iam.OrganizeVO;
import com.yunxi.eai.pojo.iam.PositionVO;
import com.yunxi.eai.pojo.iam.StaffVO;
import com.yunxi.hubToBaseData.service.Iam2BaseDataDubboService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.service.iam.IamOrgInfoService;
import com.yunxi.service.iam.IamUserInfoService;
import com.yunxi.tech.pojo.*;
import com.yunxi.tech.service.IamBaseDubboService;
import com.yunxi.tech.service.IamPartnerDubboService;
import com.yunxi.tech.service.IamStaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;

/**
 * Created by Administrator on 2019/5/20.
 */
/*@com.alibaba.dubbo.config.annotation.Service(version = "${demo.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)*/
public class IamDubboServiceImpl implements IamDubboService {
    private static final Logger logger = LoggerFactory.getLogger(IamDubboServiceImpl.class);
    @Autowired
    @Qualifier("iamOrgInfoServiceImpl")
    IamOrgInfoService iamOrgInfoService;
    @Autowired
    @Qualifier("iamUserInfoService")
    IamUserInfoService iamUserInfoService;
    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Autowired
    Iam2BaseDataDubboService iam2BaseDataDubboServiceImpl;
    @Autowired
    private Mapper dozerMapper;
    @Autowired
    IamStaffDubboService iamStaffDubboServiceImpl;
    @Value("${IAM.URL}")
    private String IAM_URL;
    @Value("${COMM2.URL}")
    private String COMM2_URL;
    @Value("${esb.switch}")
    private String esbSwitch;
    @Value("${UPS.URL}")
    private String UPS_URL;
    @Autowired
    private IamBaseDubboService iamBaseDubboServiceImpl;

    int iamCount = 50;

    /**
     * PMS系统发送组织信息数据给IAM系统
     *
     * @param pmsOrganizeVO
     * @return
     * @throws Exception
     */
    @Override
    public ApiResult sendIamOrganizeVO(List pmsOrganizeVO) throws Exception {
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok();
        }
        Map dataMap = new HashMap();
        dataMap.put("Total", pmsOrganizeVO.size());
        dataMap.put("Data", pmsOrganizeVO);
        Object bodyStr = JSONObject.toJSON(dataMap);
        ApiResult apiResult = null;
        EaiLog eaiLog = new EaiLog();
        eaiLog.setPmsEaiContent(bodyStr.toString());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送组织信息数据给IAM系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_ORG);
        try {
            Map map = HttpUtil.sendPost(bodyStr.toString(), Constant.PMS_ORG, Constant.PMS, IAM_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            Object object = map.get("header");
            JSONObject header = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag = String.valueOf(header.get("statusFlag"));
            //ESB头中的statusFlag 0失败，1成功
            if (statusFlag.equals("0")) {
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail();
            } else {
                apiResult = ResponseUtil.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用IAM系统，传递渠道组织信息，处理不成功！");
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            apiResult = ResponseUtil.fail();
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            logger.debug("mq发送成功==============");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("mq发送失败==============");
            apiResult = ResponseUtil.fail();
        }
        return apiResult;
    }

    /**
     * PMS系统发送人员信息数据给IAM系统
     *
     * @param pmsUserVO
     * @return
     * @throws Exception
     */
    @Override
    public ApiResult sendIamUserVO(List<PmsUserVO> pmsUserVO) throws Exception {
        //账号增加前缀
        //pmsUserVO.setAccount("PMS_" + pmsUserVO.getAccount());
        //密码加密
        //pmsUserVO.setPassword(DESUtil.decrypt(pmsUserVO.getPassWord()));
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok();
        }
        Map dataMap = new HashMap();
        dataMap.put("Total", pmsUserVO.size());
        dataMap.put("Data", pmsUserVO);
        Object bodyStr = JSONObject.toJSON(dataMap);
        ApiResult apiResult = null;
        EaiLog eaiLog = new EaiLog();
        eaiLog.setPmsEaiContent(bodyStr.toString());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送人员信息数据给IAM系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_USER);
        try {
            Map map = HttpUtil.sendPost(bodyStr.toString(), Constant.PMS_USER, Constant.PMS, COMM2_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(COMM2_URL);
            Object object = map.get("header");
            JSONObject header = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag = String.valueOf(header.get("statusFlag"));
            if (statusFlag.equals("0")) {
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail();
            } else {
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                if (String.valueOf(jsonResponse.get("reslut")).equals("false")) {
                    //处理失败，更状态位失败
                    eaiLog.setDisposeStatus(2);
                    apiResult = ResponseUtil.fail();
                } else {
                    apiResult = ResponseUtil.ok(map.get("response"));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("调用IAM系统，传递渠道人员信息，处理不成功！");
            eaiLog.setDisposeStatus(2);
            apiResult = ResponseUtil.fail();
        }
        try {
            for (int i = 0; i < pmsUserVO.size(); i++) {
                Object partnerInfoVO = pmsUserVO.get(i);
                StaffReqVO var1 = dozerMapper.map(partnerInfoVO, StaffReqVO.class);
                ApiResult upsResult = iamStaffDubboServiceImpl.saveStaff(var1);
                if (upsResult.getCode() != 200) {
                    eaiLog.setDisposeStatus(3);
                }
            }
        } catch (Exception e) {
            //调用UPS系统失败
            eaiLog.setDisposeStatus(3);
            logger.error(e.getMessage(), e);
            logger.error("调用UPS系统失败===========");
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            logger.debug("mq发送成功==============");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("mq发送失败==============");
            apiResult = ResponseUtil.fail();
        }
        return apiResult;
    }

    /**
     * 通过开始时间结束时间，接口拉取IAM数据
     *
     * @param serviceName
     * @param beginTime
     * @param endTime
     * @return
     * @throws Exception
     */
    @Override
    public ApiResult findDataByConditional(String serviceName, String beginTime, String endTime) throws Exception {
        ApiResult object = ResponseUtil.ok();
        if (serviceName.equals(Constant.IAM_ORG)) {
            object = findOrganizeData(serviceName, beginTime, endTime);
        } else if (serviceName.equals(Constant.IAM_USER)) {
            object = findStaffData(serviceName, beginTime, endTime);
        } else if (serviceName.equals(Constant.IAM_POST)) {
            object = findPostData(serviceName, beginTime, endTime);
        }
        return object;
    }
    /**
     * 通过开始时间结束时间，接口拉取IAM数据
     *
     * @param serviceName
     * @param beginTime
     * @param endTime
     * @return
     * @throws Exception
     */
    @Override
    public ApiResult findUpsUserByConditional(String serviceName,String iamSystem, String beginTime, String endTime) throws Exception {
        ApiResult object = ResponseUtil.ok();
      if (serviceName.equals(Constant.IAM_USER)) {
            object = findUpsStaffData(serviceName, iamSystem, beginTime, endTime);
        }
        return object;
    }

    private ApiResult findUpsStaffData(String serviceName, String iamSystem, String beginTime, String endTime) throws Exception {
        ApiResult apiResult = null;
        int pageIndex = 1;
        int pageSize = 1;
        String sourceSystem = Constant.PMS;
        String url = IAM_URL;
        //第一次传递获取总数量
        String response = findUpsDataJson(serviceName, iamSystem, sourceSystem, url, pageIndex, pageSize, beginTime, endTime);
        if (response.equals("")) {
            return ResponseUtil.fail();
        }
        JSONObject jsonObject = JSON.parseObject(response);
        int total = Integer.parseInt(String.valueOf(jsonObject.get("Total")));
        if (total > iamCount) {
            //总数大于300调需要遍历获取
            int count = MathUtil.getCount(total, iamCount);
            for (int i = 0; i < count; i++) {
                String json = findUpsDataJson(serviceName, iamSystem, sourceSystem, url, i + 1, iamCount, beginTime, endTime);
                if (json.equals("")) {
                    return ResponseUtil.fail();
                } else {
                    syncUpsStaff(json);
                }

            }
        } else {
            //小于最大获取条数
            String json = findUpsDataJson(serviceName, iamSystem, sourceSystem, url, 1, iamCount, beginTime, endTime);
            if (json.equals("")) {
                return ResponseUtil.fail();
            } else {
                syncUpsStaff(json);
            }


        }

        return apiResult;
    }

    private ApiResult syncUpsStaff(String json) {
        ApiResult apiResult = null;
        JSONObject responseObject = JSON.parseObject(json);
        Object data = responseObject.get("Data");
        ArrayList<StaffVO> staffList = JSON.parseObject(String.valueOf(data), new TypeReference<ArrayList<StaffVO>>() {
        });
        EaiLog eaiLog = new EaiLog();
        String staff = JSONObject.toJSONString(staffList);
        eaiLog.setEsbEaiContent(staff);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送人员数据给PMS系统");
        eaiLog.setServiceName(Constant.IAM_USER);
        eaiLog.setSourceSystem("EAI");
        //调人员业务接口保存数据
        List iamStaffList = new ArrayList();
       for (int i = 0; i < staffList.size(); i++) {
            StaffVO staffVO = staffList.get(i);
            IamStaff iamStaff = dozerMapper.map(staffVO, IamStaff.class);
            iamStaffList.add(iamStaff);
        }
        try {
            List<com.yunxi.tech.pojo.IamStaff> var1 = new ArrayList<>();
            for (int i = 0; i < iamStaffList.size(); i++) {
                IamStaff iamStaff = (IamStaff) iamStaffList.get(i);
                com.yunxi.tech.pojo.IamStaff iamStaff1 = new com.yunxi.tech.pojo.IamStaff();
                BeanUtils.copyProperties(iamStaff, iamStaff1);
                var1.add(iamStaff1);
            }
            iamBaseDubboServiceImpl.syncStaff(var1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(3);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            apiResult = ResponseUtil.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
        }
        logger.debug("mq发送成功==============");
        return apiResult;
    }

    @Override
    public ApiResult sendPmsPost(List<PmsPostVO> pmsPostVO) throws Exception {
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok();
        }
        Object bodyStr = JSONObject.toJSON(pmsPostVO);
        ApiResult apiResult = null;
        EaiLog eaiLog = new EaiLog();
        eaiLog.setPmsEaiContent(bodyStr.toString());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送渠道岗位信息");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_POST);
        try {
            Map map = HttpUtil.sendPost(bodyStr.toString(), Constant.PMS_POST, Constant.PMS, UPS_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            Object object = map.get("header");
            JSONObject header = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag = String.valueOf(header.get("statusFlag"));
            //ESB头中的statusFlag 0失败，1成功
            if (statusFlag.equals("0")) {
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail();
            } else {
                apiResult = ResponseUtil.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("传递渠道岗位信息，处理不成功！");
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            apiResult = ResponseUtil.fail();
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            logger.debug("mq发送成功==============");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("mq发送失败==============");
            apiResult = ResponseUtil.fail();
        }
        return apiResult;
    }


    public ApiResult findOrganizeData(String serviceName, String beginTime, String endTime) throws Exception {
        ApiResult apiResult = null;
        int pageIndex = 1;
        int pageSize = 1;
        String sourceSystem = Constant.PMS;
        String url = IAM_URL;
        //第一次传递获取总数量
        String response = findDataJson(serviceName, sourceSystem, url, pageIndex, pageSize, beginTime, endTime);
        if (response.equals("")) {
            return ResponseUtil.fail();
        }
        JSONObject jsonObject = JSON.parseObject(response);
        int total = Integer.parseInt(String.valueOf(jsonObject.get("Total")));
        if (total > iamCount) {
            //总数大于300调需要遍历获取
            int count = MathUtil.getCount(total, iamCount);
            for (int i = 0; i < count; i++) {
                String json = findDataJson(serviceName, sourceSystem, url, i + 1, iamCount, beginTime, endTime);
                if (json.equals("")) {
                    return ResponseUtil.fail();
                } else {
                    syncOrg(json);
                }

            }
        } else {
            //小于最大获取条数
            String json = findDataJson(serviceName, sourceSystem, url, 1, iamCount, beginTime, endTime);
            if (json.equals("")) {
                return ResponseUtil.fail();
            } else {
                syncOrg(json);
            }

        }
        return apiResult;
    }

    private ApiResult syncOrg(String json) throws Exception {
        ApiResult apiResult = null;
        JSONObject responseObject = JSON.parseObject(json);
        Object data = responseObject.get("Data");
        if (!data.equals("")) {
            ArrayList<OrganizeVO> orgList = JSON.parseObject(String.valueOf(data), new TypeReference<ArrayList<OrganizeVO>>() {
            });
            String org = JSONObject.toJSONString(orgList);
            EaiLog eaiLog = new EaiLog();
            eaiLog.setEsbEaiContent(org);
            eaiLog.setRequestSendTime(new Date());
            eaiLog.setFlowDesc("EAI系统发送组织数据给PMS系统");
            eaiLog.setServiceName(Constant.IAM_ORG);
            eaiLog.setSourceSystem("EAI");
            //调组织结构业务接口保存数据
            List<IamOrg> iamOrgs = BeanTools.copyListToList(orgList, IamOrg.class);
            try {
                iam2BaseDataDubboServiceImpl.syncOrg(iamOrgs);
                apiResult = ResponseUtil.ok();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                apiResult = ResponseUtil.fail();
                eaiLog.setDisposeStatus(2);
            }
            try {
                List<com.yunxi.tech.pojo.IamOrg> var1 = new ArrayList<>();
                for (int i = 0; i < iamOrgs.size(); i++) {
                    IamOrg iamOrg = iamOrgs.get(i);
                    com.yunxi.tech.pojo.IamOrg iamOrg1 = new com.yunxi.tech.pojo.IamOrg();
                    BeanUtils.copyProperties(iamOrg, iamOrg1);
                    var1.add(iamOrg1);
                }
                iamBaseDubboServiceImpl.syncOrg(var1);
                apiResult = ResponseUtil.ok();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                eaiLog.setDisposeStatus(3);
            }
            try {
                eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
                apiResult = ResponseUtil.ok();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                apiResult = ResponseUtil.fail();
            }
            logger.debug("mq发送成功==============");
        }

        return apiResult;
    }


    public ApiResult findStaffData(String serviceName, String beginTime, String endTime) throws Exception {
        ApiResult apiResult = null;
        int pageIndex = 1;
        int pageSize = 1;
        String sourceSystem = Constant.PMS;
        String url = IAM_URL;
        //第一次传递获取总数量
        String response = findDataJson(serviceName, sourceSystem, url, pageIndex, pageSize, beginTime, endTime);
        if (response.equals("")) {
            return ResponseUtil.fail();
        }
        JSONObject jsonObject = JSON.parseObject(response);
        int total = Integer.parseInt(String.valueOf(jsonObject.get("Total")));
        if (total > iamCount) {
            //总数大于300调需要遍历获取
            int count = MathUtil.getCount(total, iamCount);
            for (int i = 0; i < count; i++) {
                String json = findDataJson(serviceName, sourceSystem, url, i + 1, iamCount, beginTime, endTime);
                if (json.equals("")) {
                    return ResponseUtil.fail();
                } else {
                    syncStaff(json);
                }

            }
        } else {
            //小于最大获取条数
            String json = findDataJson(serviceName, sourceSystem, url, 1, iamCount, beginTime, endTime);
            if (json.equals("")) {
                return ResponseUtil.fail();
            } else {
                syncStaff(json);
            }


        }

        return apiResult;
    }

    private ApiResult syncStaff(String json) throws Exception {
        ApiResult apiResult = null;
        JSONObject responseObject = JSON.parseObject(json);
        Object data = responseObject.get("Data");
        ArrayList<StaffVO> staffList = JSON.parseObject(String.valueOf(data), new TypeReference<ArrayList<StaffVO>>() {
        });
        EaiLog eaiLog = new EaiLog();
        String staff = JSONObject.toJSONString(staffList);
        eaiLog.setEsbEaiContent(staff);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送人员数据给PMS系统");
        eaiLog.setServiceName(Constant.IAM_USER);
        eaiLog.setSourceSystem("EAI");
        //调人员业务接口保存数据
        List iamStaffList = new ArrayList();
        for (int i = 0; i < staffList.size(); i++) {
            StaffVO staffVO = staffList.get(i);
            IamStaff iamStaff = dozerMapper.map(staffVO, IamStaff.class);
            iamStaffList.add(iamStaff);
        }
        try {
            iam2BaseDataDubboServiceImpl.syncStaff(iamStaffList);
            apiResult = ResponseUtil.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
    /*    try {
            List<com.yunxi.tech.pojo.IamStaff> var1 = new ArrayList<>();
            for (int i = 0; i < iamStaffList.size(); i++) {
                IamStaff iamStaff = (IamStaff) iamStaffList.get(i);
                com.yunxi.tech.pojo.IamStaff iamStaff1 = new com.yunxi.tech.pojo.IamStaff();
                BeanUtils.copyProperties(iamStaff, iamStaff1);
                var1.add(iamStaff1);
            }
            iamBaseDubboServiceImpl.syncStaff(var1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(3);
        }*/
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            apiResult = ResponseUtil.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
        }
        logger.debug("mq发送成功==============");
        return apiResult;
    }

    private ApiResult findPostData(String serviceName, String beginTime, String endTime) throws Exception {
        ApiResult apiResult = null;
        int pageIndex = 1;
        int pageSize = 1;
        String sourceSystem = Constant.PMS;
        String url = IAM_URL;
        //第一次传递获取总数量
        String response = findDataJson(serviceName, sourceSystem, url, pageIndex, pageSize, beginTime, endTime);
        if (response.equals("")) {
            return ResponseUtil.fail();
        }
        JSONObject jsonObject = JSON.parseObject(response);
        int total = Integer.parseInt(String.valueOf(jsonObject.get("Total")));
        if (total > iamCount) {
            //总数大于300调需要遍历获取
            int count = MathUtil.getCount(total, iamCount);
            for (int i = 0; i < count; i++) {
                System.out.println(i + "=============================");
                String json = findDataJson(serviceName, sourceSystem, url, i + 1, iamCount, beginTime, endTime);
                if (json.equals("")) {
                    return ResponseUtil.fail();
                } else {
                    syncPos(json);
                }
            }
        } else {
            //小于最大获取条数
            String json = findDataJson(serviceName, sourceSystem, url, 1, iamCount, beginTime, endTime);
            if (json.equals("")) {
                return ResponseUtil.fail();
            } else {
                syncPos(json);
            }
        }
        return apiResult;
    }

    private ApiResult syncPos(String json) throws Exception {
        ApiResult apiResult = null;
        JSONObject responseObject = JSON.parseObject(json);
        Object data = responseObject.get("Data");
        ArrayList<PositionVO> postList = JSON.parseObject(String.valueOf(data), new TypeReference<ArrayList<PositionVO>>() {
        });
        String post = JSONObject.toJSONString(postList);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(post);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setServiceName(Constant.IAM_POST);
        eaiLog.setSourceSystem("EAI");
        eaiLog.setFlowDesc("EAI系统发送职务数据给PMS系统");
        //调职务业务接口保存数据
        //调组织结构业务接口保存数据
        List<IamPos> iamPosList = BeanTools.copyListToList(postList, IamPos.class);
        try {
            iam2BaseDataDubboServiceImpl.syncPos(iamPosList);
            apiResult = ResponseUtil.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            List<com.yunxi.tech.pojo.IamPos> var1 = new ArrayList<>();
            for (int i = 0; i < iamPosList.size(); i++) {
                IamPos iamPos = iamPosList.get(i);
                com.yunxi.tech.pojo.IamPos iamPos1 = new com.yunxi.tech.pojo.IamPos();
                BeanUtils.copyProperties(iamPos, iamPos1);
                var1.add(iamPos1);
            }
            iamBaseDubboServiceImpl.syncPos(var1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(3);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            apiResult = ResponseUtil.ok();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
        }
        logger.debug("mq发送成功==============");
        return apiResult;
    }

    private String findUpsDataJson(String serviceName, String iamSystem, String sourceSystem, String url, int i, int j, String beginTime, String endTime) throws Exception {
        String jsonStr = "";
        String datajson = "";
        EaiLog eaiLog = new EaiLog();
        if (serviceName.equals(Constant.IAM_USER)) {
            jsonStr = getStaffData(i, j, beginTime, endTime);
            eaiLog.setFlowDesc("PMS系统请求IAM系统获取厂端人员信息");
        }
        eaiLog.setPmsEaiContent(jsonStr);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setSourceSystem(sourceSystem);
        eaiLog.setServiceName(serviceName);
        try {
            Map map = HttpUtil.sendUpsPost(jsonStr, serviceName, sourceSystem, url, iamSystem);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            Object object = map.get("header");
            JSONObject header = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag = String.valueOf(header.get("statusFlag"));
            if (statusFlag.equals("0")) {//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
            } else {
                datajson = String.valueOf(map.get("response"));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(2);
            logger.error("调用ESB系统失败===========");
            datajson = "";
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            logger.debug("mq发送成功==============");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("mq发送失败==============");
            datajson = "";
        }

        return datajson;
    }

    private String findDataJson(String serviceName, String sourceSystem, String url, int i, int j, String beginTime, String endTime) throws Exception {
        String jsonStr = "";
        String datajson = "";
        EaiLog eaiLog = new EaiLog();
        if (serviceName.equals(Constant.IAM_ORG)) {
            jsonStr = getOrganizeData(i, j, beginTime, endTime);
            eaiLog.setFlowDesc("PMS系统请求IAM系统获取厂端组织信息");
        } else if (serviceName.equals(Constant.IAM_USER)) {
            jsonStr = getStaffData(i, j, beginTime, endTime);
            eaiLog.setFlowDesc("PMS系统请求IAM系统获取厂端人员信息");
        } else if (serviceName.equals(Constant.IAM_POST)) {
            jsonStr = getPostData(i, j, beginTime, endTime);
            eaiLog.setFlowDesc("PMS系统请求IAM系统获取厂端职务信息");
        }
        eaiLog.setPmsEaiContent(jsonStr);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setSourceSystem(sourceSystem);
        eaiLog.setServiceName(serviceName);
        try {
            Map map = HttpUtil.sendPost(jsonStr, serviceName, sourceSystem, url);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            Object object = map.get("header");
            JSONObject header = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag = String.valueOf(header.get("statusFlag"));
            if (statusFlag.equals("0")) {//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
            } else {
                datajson = String.valueOf(map.get("response"));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(2);
            logger.error("调用ESB系统失败===========");
            datajson = "";
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
            logger.debug("mq发送成功==============");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("mq发送失败==============");
            datajson = "";
        }

        return datajson;
    }

    private String getStaffData(int pageIndex, int pageSize, String beginTime, String endTime) throws ParseException {
        Map map = new HashMap();
        Map extParamsMap = new HashMap();
        Map sortMap = new HashMap();
        List empList = getEmpList();
        List employList = getEmployList();
        List serviceList = getServiceList();
        map.put("StartTime", DateUtil.getUtcTime(beginTime));
        map.put("StopTime", DateUtil.getUtcTime(endTime));
        map.put("WithDisabled", true);
        map.put("WithDeleted", true);
        map.put("PageIndex", pageIndex);//1
        map.put("PageSize", pageSize);//300
        map.put("Sort", sortMap);
        map.put("ExtParams", extParamsMap);
        map.put("IsGetLatestRecord", true);
        map.put("EmpStatus", empList);
        map.put("EmployType", employList);
        map.put("ServiceType", serviceList);
        StaffVO staffVO = new StaffVO();
        Field[] field = staffVO.getClass().getDeclaredFields();
        List list = new ArrayList();
        for (int j = 0; j < field.length; j++) { // 遍历所有属性
            list.add(field[j].getName());
        }
        map.put("Columns", list);
        Object json = JSONObject.toJSON(map);
        return json.toString();
    }

    private List getServiceList() {
        List serviceList = new ArrayList();
        serviceList.add(0);
        serviceList.add(1);
        serviceList.add(2);
        serviceList.add(3);
        serviceList.add(4);
        return serviceList;
    }

    private List getEmployList() {
        List employList = new ArrayList();
        employList.add(0);
        employList.add(1);
        employList.add(2);
        return employList;
    }

    private List getEmpList() {
        List empList = new ArrayList();
        empList.add(0);
        empList.add(1);
        empList.add(2);
        empList.add(3);
        empList.add(4);
        empList.add(5);
        empList.add(6);
        empList.add(7);
        empList.add(8);
        empList.add(9);
        empList.add(10);
        empList.add(11);
        empList.add(12);
        return empList;
    }


    private String getOrganizeData(int pageIndex, int pageSize, String beginTime, String endTime) throws ParseException {
        Map map = new HashMap();
        Map SortMap = new HashMap();
        Map ExtParamsMap = new HashMap();
        map.put("StartTime", DateUtil.getUtcTime(beginTime));
        map.put("StopTime", DateUtil.getUtcTime(endTime));
        map.put("WithDisabled", true);
        map.put("WithDeleted", true);
        map.put("PageIndex", pageIndex);//1
        map.put("PageSize", pageSize);//300
        map.put("Sort", SortMap);
        map.put("ExtParams", ExtParamsMap);
        OrganizeVO organizeVO = new OrganizeVO();
        Field[] field = organizeVO.getClass().getDeclaredFields();
        List list = new ArrayList();
        for (int j = 0; j < field.length; j++) { // 遍历所有属性
            list.add(field[j].getName());
        }
        map.put("Columns", list);
        Object json = JSONObject.toJSON(map);
        return json.toString();
    }

    private String getPostData(int pageIndex, int pageSize, String beginTime, String endTime) throws ParseException {
        Map map = new HashMap();
        Map extParamsMap = new HashMap();
        Map sortMap = new HashMap();
        map.put("StartTime", DateUtil.getUtcTime(beginTime));
        map.put("StopTime", DateUtil.getUtcTime(endTime));
        map.put("WithDisabled", true);
        map.put("WithDeleted", true);
        map.put("PageIndex", pageIndex);//1
        map.put("PageSize", pageSize);//300
        map.put("Sort", sortMap);
        map.put("ExtParams", extParamsMap);
        PositionVO positionVO = new PositionVO();
        Field[] field = positionVO.getClass().getDeclaredFields();
        List list = new ArrayList();
        for (int j = 0; j < field.length; j++) { // 遍历所有属性
            list.add(field[j].getName());
        }
        map.put("Columns", list);
        Object json = JSONObject.toJSON(map);
        return json.toString();
    }


}
